﻿using Fuse8.DomainFramework.BusinessService;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.GlobalizationFramework.BusinessServices;
using Fuse8.GlobalizationFramework.DataAccess.SqlRepository;
using Fuse8.GlobalizationFramework.Domain;
using Microsoft.Practices.Unity;

namespace Fuse8.GlobalizationFramework.Infrastructure
{
    internal class Policy
    {
        private static bool isInited;

        public static void InitDependicies()
        {
            if (isInited)
            {
                return;
            }

            if (DependencyServiceLocator.Current == null)
            {
                InitServiceLocator();
            }

            if (!DependencyServiceLocator.Current.IsRegistered<IGlobalizationSetting>())
            {
                DependencyServiceLocator.Current.SetDefaultService<IGlobalizationSetting>(
                    new DefaultGlobalizationSetting());
            }

            if (!DependencyServiceLocator.Current.IsRegistered<IEntityBusinessService<Resource, int>>())
            {
                DependencyServiceLocator.Current.SetDefaultService<IEntityBusinessService<Resource, int>>(new GlobalizableBusinessService<Resource>()); 
            }
            
            if (!DependencyServiceLocator.Current.IsRegistered<IEntityDataRepository<Resource, int>>())
            {
                NativeDataAccessPolicy.Init();
            }

            isInited = true;
        }

        private static void InitServiceLocator()
        {
            IUnityContainer container = new UnityContainer();
            var locator = new UnityServiceLocatorWithLazy(container);
            DependencyServiceLocator.SetLocatorProvider(() => locator);
        }
    }
}